﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Office.Interop.Access;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace BuildDelivery {
    /// <summary>
    /// Allows for the following actions to be done on an access database:
    ///    Compact/Repair,
    ///    Compile VBA code,
    ///    Make MDE File.
    /// Note: Do not open the files before running these procedures.
    /// </summary>
    public static class AccessDB {

        public static Application app = null;

        /// <summary>
        /// Compiles the VBA, then compacts and repairs, then makes and returns the MDE file.
        /// Note: this uses an undocumented Access SysCmd 603 for making MDE files. 
        ///       This works on Access 2003, but any other version is suspect.
        /// </summary>
        /// <param name="mdbFile"></param>
        /// <returns>mde file</returns>
        public static FileInfo FullCompileToMDE(FileInfo mdbFile) {
            Application app = OpenAccessApplication();

            CompileVBA(mdbFile);
            CompactAndRepair(mdbFile);
            FileInfo newfile = MakeMDE(mdbFile);

            CloseAccessApplication();

            return newfile;
        }
        /// <summary>
        /// Closes an access application
        /// </summary>
        /// <param name="app"></param>
        public static void CloseAccessApplication() {
            app.Quit(AcQuitOption.acQuitSaveNone);
            app = null;
        }

        /// <summary>
        /// Closes and save an access application
        /// </summary>
        /// <param name="app"></param>
        public static void CloseAccessApplicationSaveAll()
        {
            if (app != null)
            {
                app.Quit(AcQuitOption.acQuitSaveAll);
                //app.CloseCurrentDatabase();
                Marshal.ReleaseComObject(app);
            }
            else
                app = null;

            CloseAllAccessProcesses();
        }

        public static void CloseAllAccessProcesses()
        {
            foreach (Process proc in System.Diagnostics.Process.GetProcessesByName("MSACCESS"))
            {
                proc.Kill();
            }
        }

        /// <summary>
        /// Makes an MDE file.
        /// Note: this uses an undocumented Access SysCmd 603 for making MDE files.
        ///        This works on Access 2003, but any other version is suspect.
        /// </summary>
        /// <param name="mdbFile"></param>
        /// <param name="app"></param>
        /// <returns>mde file</returns>
        public static FileInfo MakeMDE(FileInfo mdbFile)
        {
            string newfilename = mdbFile.FullName;
            newfilename = newfilename.Remove(newfilename.Length - 1) + 
                                      "e";//switch from MDB to MDE
            //SysCmd is undocumented, and #603 is especially undocumented.
            app.SysCmd((AcSysCmdAction)603, mdbFile.FullName, newfilename);
            return new FileInfo(newfilename);
        }
        /// <summary>
        /// Compacts and repairs an Access database
        /// </summary>
        /// <param name="accessFile"></param>
        /// <param name="app"></param>
        public static void CompactAndRepair(FileInfo accessFile)
        {
            string tempFile = Path.Combine(accessFile.Directory.FullName, 
                              Path.GetRandomFileName() + accessFile.Extension);
            
            app.CompactRepair(accessFile.FullName, tempFile, false);
            app.Visible = false;

            FileInfo temp = new FileInfo(tempFile);
            temp.CopyTo(accessFile.FullName, true);
            temp.Delete();
        }
        /// <summary>
        /// Opens an access application
        /// </summary>
        /// <returns></returns>
        public static Application OpenAccessApplication()
        {
            app = new Application();
            app.Visible = false;
            return app;
        }
        /// <summary>
        /// Compiles the VBA for an Access database
        /// </summary>
        /// <param name="mdbFile"></param>
        /// <param name="app"></param>
        public static void CompileVBA(FileInfo mdbFile)
        {
            app.OpenCurrentDatabase(mdbFile.FullName, true, "");
            if (!app.IsCompiled) {
                //c.DoCmd.OpenModule(c.CurrentDb().
                //   Containers["Modules"].Documents[0].Name, Type.Missing);
                app.RunCommand(AcCommand.acCmdCompileAndSaveAllModules);
            }
            app.CloseCurrentDatabase();
            app.Visible = false;
        }
    }
}